#include<stdio.h>

typedef int ElemType;

//创建链表
typedef struct node
{
    ElemType data;
    struct node *next; 
}Node;

//单链表的初始化
Node* initList()
{   //创建头节点
    Node *head = (Node*)malloc(sizeof(Node));
    head->data = 0;
    head->next = NULL;
    return head;   //返回head指针
}

//单链表-头插法(每一次把数据插在头节点后面)
int insertHead(Node *L, ElemType e)
{
    Node *p = (Node*)malloc(sizeof(Node));
    p->data = e;
    p->next = L->next; //头节点的指针部分给了新结点的指针部分
    L->next = p; //头节点的指针指向新结点
    return 1;
}

//单链表-遍历
void listNode(Node *L)
{
    Node *p = L->next;
    while(p != NULL)
    {
        printf("%d\n",p->data);
        p = p->next;
    }
    printf("\n");
}

//单链表-尾插法
//获取尾节点
Node* get_tail(Node *L)
{
    Node *p = L;
    while(p->next != NULL)
    {
        p = p->next;
    }
    return p;
}
//尾部插入
Node* insertTial(Node *tail,ElemType e)
{
    Node *p = (Node*)malloc(sizeof(Node));
    p->data = e;
    tail->next = p;
    p->next = NULL;
    return p;
}

//单链表-在指定位置插入节点
int insertNode(Node *L,int pos,ElemType e)
{
    //找到插入位置
    Node *p = L;
    int i = 0;
    while(i < pos -1)
    {
        p = p->next;
        i++;
        if(p == NULL)
        {
            return 0;
        }
    }
    //创建节点
    Node *q = (Node*)malloc(sizeof(Node));
    q->data = e;
    q->next = p->next;
    p->next = q;
    return 1;
}

//单链表-删除节点
int delectNode(Node *L, int pos)
{   
    //p找到删除节点的前置节点
    Node *p = L;
    int i = 0;
    while(i < pos -1)
    {
        p = p->next;
        i++;
        if(p == NULL)
        {
            return 0;
        }
    }

    if(p->next == NULL)
    {
        printf("删除节点有误\n");
        return 0;
    }
    //q指向要删除的节点
    Node *q = p->next;
    //让要删除节点的前驱指向要删除节点的后继
    p->next = q->next;
    free(q);
    return 1;
}

//单链表-获取链表长度
int listLength(Node *L)
{
    Node *p = L;
    int len = 0;
    while(p != NULL)
    {
        p = p->next;
        len++;
    }
    return len;
}

//释放链表
void freeList(Node *L)
{
    Node *p = L->next;
    Node *q;
    while(p != NULL)
    {
        q = p->next;
        free(p);
        p=q;
    }
    L->next = NULL;
}

int main()
{
    Node *list = initList();
    insertHead(list,10);
    insertHead(list,20);
    return 0;
}
